<?php
namespace App\Api\Controllers\Cqcbank;


use App\Models\YinkaStore;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Rtgm\sm\RtSm4;
use Rtgm\sm\RtSm2;

use phpseclib\Crypt\RSA;
use phpseclib\Crypt\Hash;

class BaseController
{
    static $config, $instance, $data;

//    const MAIN_URL ='https://test.cqcbank.com/openapi/';
//    const MAIN_URL ='https://wxbank.test.cqcbank.com/openapi/';

    // 表单提交字符集编码
    public $postCharset = "UTF-8";

    private $fileCharset = "UTF-8";
    public  static $_apiUrl;

    public static function getInstance ()
    {
        if (! isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function params ($request, $config)
    {

        $body['commonBody'] = [
            'channelSerialNo' => Date("YmdHis").mt_rand(10000000,99999999),//交易流水号
            'appCode'         => $config->app_code,
            'version'         => '1.0',
            'signSn'          => $config->sign_sn,
            'deviceId'        => $request['terminal_id'],//设备编号
            'timestamp'       => date('Y-m-d H:i:s'),//交易时间
            'algorithm'       => 'SM3withSM2',//签名算法
        ];
        $body['request'] = $request;
        $body['key'] = $config->key;
        $body['puk'] = $config->public_rsa_key;
        $body['pvk'] = $config->private_rsa_key;

        self::$_apiUrl = $config->url;
        self::$data = $body;
        return $this;
    }

    private function getMonthDifference($start, $end)
    {
        $years = date('Y', $end) - date('Y', $start);
        $monthTotal = $years * 12 + date('m', $end) - date('m', $start);
        return $monthTotal;
    }
    public static function createSign ($params)
    {
        $str = '';
        ksort($params);
        $i = 0;
        foreach($params as $k => $v) {
            if ($v === null || $v == null || $v == '') {
                continue;
            }
            if ($i == 0) {
                $str .= "$k" . "=" . "$v";
            } else {
                $str .= "&" . "$k" . "=" . "$v";
            }
            $i++;
        }
        return $str;
    }

    public function build ($transactionID)
    {
        $url = "http://gm.wftpay.cn:8082/getCqbackSign";
        self::$data['url'] = self::$_apiUrl.$transactionID;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url); //设置选项，包括URL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);


        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(self::$data));

        $headers = array();
        $headers[] = 'Content-Type: application/json';
        $headers[] = 'Charset: UTF-8';
        $headers[] = "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3";
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $output = curl_exec($ch); //执行并获取HTML文档内容

        curl_close($ch); //释放curl句柄
        $result = json_decode($output, true);

        return $result;

    }

    public  function getSignContent($params)
    {
        ksort($params);

        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {

            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset ($k, $v);
        return $stringToBeSigned;
    }

    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value)
    {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;

        return false;
    }

    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = $this->fileCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {

                $data = mb_convert_encoding($data, $targetCharset);
                //				$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }

}